package com.ruoyi.auth.controller;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import com.ruoyi.auth.form.PassengerLoginBody;
import com.ruoyi.system.api.domain.Drivers;
import com.ruoyi.system.api.domain.Passengers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.auth.form.LoginBody;
import com.ruoyi.auth.form.RegisterBody;
import com.ruoyi.auth.service.SysLoginService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.auth.AuthUtil;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * token 控制
 * 
 * @author ruoyi
 */
@RestController
public class TokenController
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @PostMapping("sendCode")
    public R sendCode(@RequestParam String phone) {
        return sysLoginService.sendCode(phone);
    }

    @PostMapping("passengerLogin")
    public R<?> passengerLogin(@RequestBody PassengerLoginBody form)
    {
        Passengers passengers = sysLoginService.passengerLogin(form.getPhone(), form.getCode());
        LoginUser loginUser = new LoginUser();
        loginUser.setPassengers(passengers);
        loginUser.setLoginTime(System.currentTimeMillis());

        // 直接生成并返回JWT令牌
        String token = tokenService.createToken(loginUser).toString();

        // 创建响应对象
        Map<String, Object> response = new HashMap<>();
        response.put("token", token);
        response.put("user", passengers); // 如果需要返回用户信息

        return R.ok(response);
    }
    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form)
    {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }


    @PostMapping("driverLogin")
    public R<?> driverLogin(@RequestBody PassengerLoginBody form)
    {
        Drivers drivers = sysLoginService.driverLogin(form.getPhone(), form.getCode());
        LoginUser loginUser = new LoginUser();
        loginUser.setDrivers(drivers);
        loginUser.setLoginTime(System.currentTimeMillis());

        // 直接生成并返回JWT令牌
        String token = tokenService.createToken(loginUser).toString();

        // 创建响应对象
        Map<String, Object> response = new HashMap<>();
        response.put("token", token);
        response.put("user", drivers); // 如果需要返回用户信息

        return R.ok(response);
    }


    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request)
    {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @PostMapping("register")
    public R<?> register(@RequestBody RegisterBody registerBody)
    {
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return R.ok();
    }

//    public R<?> captchaImage() {
//        // 生成文字验证码
////        String text = captchaProducer.createText();
////        // 生成图片验证码
////        BufferedImage image = captchaProducer.createImage(text);
////        // 将图片转为字节数组
////        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
////        try {
////            ImageIO.write(image, "jpg", os);
////        } catch (IOException e) {
////            return R.error(e.getMessage());
////        }
////
////        // 这里可以将验证码文字存储到 Redis 等地方，用于后续验证，若依框架通常会结合 Redis 处理
////        // 示例：将验证码文字存入 Redis，设置过期时间（比如 2 分钟）
////        // redisCache.setCacheObject(Constants.CAPTCHA_CODE_KEY + uuid, text, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
////
////        // 返回结果，一般包含图片字节数组和一个唯一标识（比如 uuid，用于关联验证码文字）
////        // 若依框架中常用的返回结构，这里简单示例，可根据实际调整
////        return R.ok().put("img", os.toByteArray()).put("uuid", "这里生成唯一标识，比如 UUID.randomUUID().toString()");
//    }
}
